package org.vt.ece4564.pcw.assignment2;

import java.io.IOException;

import java.util.List;

import javax.jdo.Query;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.vt.ece4564.pcw.assignment2data.Account;
import org.vt.ece4564.pcw.assignment2data.PasswordEncrypt;

@SuppressWarnings("serial")
public class TextInClassRegisterUser extends HttpServlet {
	
	@Override
	public void init(ServletConfig servletConfig) {
		
	}
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String username = request.getParameter("username");
		String name = request.getParameter("name");
		String phoneID = request.getParameter("phoneID");
		String password = request.getParameter("password");
		String passwordReenter = request.getParameter("password_reenter");
		
		response.setContentType("text/plain");
		
		// Check for invalid characters, may use regular expressions...
		
		if (!password.equals(passwordReenter)) { //Passwords don't match
			response.getWriter().write("Error: Password Mismatch\n" + 
					password + "!=" + passwordReenter);
			return;
		}
		
		// Check for any accounts that already have that phone ID
		
		Query query1 = PMF.get().getPersistenceManager().newQuery("select from " +
				Account.class.getName()+ " where phoneID_==phoneID");
		query1.declareParameters("String phoneID");
		
		@SuppressWarnings("unchecked")
		List<Account> account1 = (List<Account>) query1.execute(phoneID);
		
		if (account1.size() != 0) {
			response.getWriter().write("Error: An account already exists for that phone");
			return;
		}
		
		// Check for any accounts that already have that username
		
		Query query2 = PMF.get().getPersistenceManager().newQuery("select from " + 
				Account.class.getName() + " where username_==user");
		query2.declareParameters("String user");
		
		@SuppressWarnings("unchecked")
		List<Account> accounts = (List<Account>) query2.execute(username);
		
		if (accounts.size() != 0) { //This name is taken
			response.getWriter().write("Error: Username " + username + " is taken");
			return;
		}
		
		String passwordDigest = PasswordEncrypt.encrypt(password);
		
		if (passwordDigest.equals("?")) { //Failed to encrypt password
			response.getWriter().write("Error: Unable to encrypt password");
			return;
		}
		
		Account account = new Account(username, name, phoneID, passwordDigest);
		
		PMF.get().getPersistenceManager().makePersistent(account);
		
		response.getWriter().write("Success");
		
	}
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws IOException {
		response.sendRedirect("/registerUser.html");
	}
	
}
